import { Delete, FolderClose } from '@icon-park/react'
import { NavLink, useFetcher, useSubmit } from 'react-router-dom'
import { useStore } from '@renderer/store/useStore'
import { useContextMenu } from 'mantine-contextmenu'
import useContent from '@renderer/hooks/useContent'

interface Props {
  category: CategoryType
}
export default function CategoryItem({ category }: Props) {
  // fetcher里面的submit方法，不会刷新页面，只会刷新组件内容
  // 而useSubmit里面的submit方法，会刷新页面
  const submit = useSubmit()
  const fetcher = useFetcher()
  const { showContextMenu } = useContextMenu()
  const { dragHandle } = useContent(category)

  const editCategoryId = useStore((state) => state.editCategoryId)
  const setEditCategoryId = useStore((state) => state.setEditCategoryId)

  const contextMenu = (category: CategoryType) => {
    return showContextMenu(
      [
        {
          key: 'del',
          icon: <Delete theme="outline" size="18" />,
          title: '删除分类',
          onClick: () => {
            submit({ id: category.id }, { method: 'DELETE' })
          }
        }
      ],
      { className: 'contextMenu' }
    )
  }

  return (
    <>
      {editCategoryId == category.id ? (
        <div className="input-box">
          <input
            autoFocus
            name="name"
            defaultValue={category.name}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                fetcher.submit({ id: category.id, name: e.currentTarget.value }, { method: 'PUT' })
                setEditCategoryId(0)
              }
            }}
          />
        </div>
      ) : (
        <NavLink
          to={`/config/category/contentList/${category.id}`}
          key={category.id}
          onDoubleClick={() => {
            setEditCategoryId(category.id)
          }}
          onContextMenu={contextMenu(category)}
          {...dragHandle}
        >
          <div className="flex items-center gap-1">
            <FolderClose theme="outline" size="12" strokeWidth={3} />
            <div className="truncate">{category.name}</div>
          </div>
        </NavLink>
      )}
    </>
  )
}
